package com.example.dell.mymusicplayer;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity implements View.OnClickListener , SeekBar.OnSeekBarChangeListener {

    private ImageView img_1,img_2,img_3;
    private TextView te_1,te_2;
    private SeekBar seekBar;
    private ListView listView;
    private MediaPlayer mPlay = new MediaPlayer();
    private ArrayList<MusicData> musicDataArrayList;
    private MusicData musicData;
    private Timer timer;
    private TimerTask timerTask;
    private Handler handler;
    private int duration = 0;
    private int time = 0;
    private RelativeLayout relativeLayout;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private int currIndex = 2;//播放当前的音乐索引
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
//    private View root_Layout;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        handler = new Handler() {
            int num = 0;
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        Log.i("444444"," "+num);
                        te_1.setText(formatTime(num+=1000));
                        if(formatTime(num).equals(formatTime(mPlay.getDuration()))){
                            timer.cancel();
                        }
                        break;
                    case 2:
                        if (seekBar.getProgress() < mPlay.getDuration()) {
                            Log.i("88888","999999");
                            //进度条前进一秒

                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            handler.sendEmptyMessageDelayed(0, 1000);
                            //修改显示当前进度的文本
//                            te_1.setText(formatTime(mPlay.getCurrentPosition()));
                            time += 1000;
                        }
                        break;
                }
                super.handleMessage(msg);
            }
        };
        verifyStoragePermissions(this);
        initMusicList();
        initListView();

    }

    public  void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.READ_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init(){
        relativeLayout = (RelativeLayout) findViewById(R.id.rela);
        img_1 = (ImageView) findViewById(R.id.before);
        img_2 = (ImageView) findViewById(R.id.stop);
        img_3 = (ImageView) findViewById(R.id.next);
        te_1 = (TextView) findViewById(R.id.te_1);
        te_2 = (TextView) findViewById(R.id.te_2);
        listView = (ListView) findViewById(R.id.listview);
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);


                Message mm = new Message();
                mm.what = 2;
                Log.i("789789","456123");
                handler.sendMessage(mm);
            }
        };
        setOnclick();
    }

    public void setOnclick(){
        img_1.setOnClickListener(this);
        img_2.setOnClickListener(this);
        img_3.setOnClickListener(this);
    }

    //初始化音乐列表对象
    public void initMusicList(){
        musicDataArrayList = new ArrayList<>();
        if (musicDataArrayList.isEmpty()){
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            Log.i("123123",mMusicCursor+"123123");
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);

            for (mMusicCursor.moveToFirst();!mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()){
                String strTitle = mMusicCursor.getString(indexTitle);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);
                String strArtist = mMusicCursor.getString(indexArtist);
                Log.i("456456",strTotoalTime+"   "+strPath+"   "+strArtist);
                musicData = new MusicData(strTitle,strTotoalTime,strPath,strArtist);
                musicDataArrayList.add(musicData);
            }
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_theme:
                new android.app.AlertDialog.Builder(this)
                        .setTitle("请选择主题").
                        setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        Toast.makeText(MainActivity.this,"sss"+which,Toast.LENGTH_SHORT).show();
                                        Log.e("222222",which+"");
                                        PropertyBean property = new PropertyBean(MainActivity.this);
                                        String theme =property.THEMES[which];
//                                        theme= PropertyBean.THEMES[which];
                                        Log.i("1111111",theme);
                                        MainActivity.this.setTheme(theme);
                                        property.setAndSaveTheme(theme);
                                    }
                                }).show();
                break;
            case R.id.menu_about:
                new android.app.AlertDialog.Builder(MainActivity.this)
                        .setTitle("GRacePlayer")
                        .setMessage(R.string.about2)
                        .show();
                break;

        }

        return super.onOptionsItemSelected(item);
    }

    //设置适配器并初始化listView
    public void initListView(){
        List<Map<String,String>> list_map = new ArrayList<>();
        HashMap<String,String> map;
        SimpleAdapter simpleAdapter;
        for (MusicData musicData:musicDataArrayList){
            map = new HashMap<String,String>();
            map.put("musicName",musicData.getMusicName());
//            map.put("musicTime",musicData.getMusicTime());
//            map.put("musicPath",musicData.getMusicPath());
            map.put("musicArtist",musicData.getMusicArtist());
            list_map.add(map);
        }
        String[] from = new String[]{"musicName","musicArtist"};
        int[] to = {R.id.listview_title_item,R.id.listview_artist_item};
        simpleAdapter = new SimpleAdapter(this,list_map,R.layout.list_adapter,from,to);
        listView.setAdapter(simpleAdapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.stop:
                Log.i("789789",mPlay+"123");
                try {
                    if (mPlay==null||mPlay.isPlaying()){
                        mPlay.stop();
                        timer.cancel();
                        te_1.setText(formatTime(0));
//                        mPlay.release();
                        mPlay.reset();

                        img_2.setBackgroundResource(R.drawable.start);
                    }else{
                        mPlay.reset();
                        mPlay.setDataSource(musicDataArrayList.get(currIndex).getMusicPath().toString());
                        mPlay.prepare();
                        mPlay.start();
                        seekBar.setMax(mPlay.getDuration());
                        timer.schedule(timerTask,1000,1000);
                        te_2.setText(formatTime(mPlay.getDuration()));;
                        seekBar.setOnSeekBarChangeListener(this);
                        img_2.setBackgroundResource(R.drawable.stop);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.before:
                if(musicDataArrayList.size()>0&&currIndex<musicDataArrayList.size()){
                    if ((currIndex-1)>=0){
                        currIndex--;
                        try {
                            mPlay.reset();
                            mPlay.setDataSource(musicDataArrayList.get(currIndex).getMusicPath().toString());
                            mPlay.prepare();
                            mPlay.start();
                            te_2.setText(formatTime(mPlay.getDuration()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    Toast.makeText(this,"以是第一首歌",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.next:
                if(musicDataArrayList.size()>0&&currIndex<musicDataArrayList.size()){
                    if (currIndex<musicDataArrayList.size()-1){
                        currIndex++;
                        try {
                            mPlay.reset();
                            mPlay.setDataSource(musicDataArrayList.get(currIndex).getMusicPath().toString());
                            mPlay.prepare();
                            mPlay.start();
                            te_2.setText(formatTime(mPlay.getDuration()));
                            Log.i("111111",currIndex+"1111");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    Toast.makeText(this,"以是最后一首歌",Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//        te_1.setText(formatTime(mPlay.getCurrentPosition()));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    //毫秒转换为分钟
    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        if(minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }

        String secondString;
        if(second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }

        return minuteString + ":" + secondString;
    }
    private void setTheme(String theme) {
        if("彩色".equals(theme)) {
            this.relativeLayout.setBackgroundResource(R.drawable.bg_color);
        } else if("花朵".equals(theme)) {
            this.relativeLayout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if("群山".equals(theme)) {
            this.relativeLayout.setBackgroundResource(R.drawable.bg_mountain);
        } else if("小狗".equals(theme)) {
            this.relativeLayout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if("冰雪".equals(theme)) {
            this.relativeLayout.setBackgroundResource(R.drawable.bg_snow);
        } else if("女孩".equals(theme)) {
            this.relativeLayout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if("朦胧".equals(theme)) {
            this.relativeLayout.setBackgroundResource(R.drawable.bg_blur);
        }
    }



}
